import React, { Component } from 'react';
import { Table, Helper, Dialog, Pagination, AntdTable, Loading } from '@knownsec/react-component';
import { localScanColumns } from '../ScanRes/columns';
import { getLocalReport, getCloudReport } from '~/API';
import s from './style.module.less';
import cn from 'classnames';
import moment from 'moment';
const STATUS=['未知','正常','异常']
const STATUS_C=['#7f7e7d','#11ab4e','#f04038']
const CusLoading = <Loading label="" />;
class TaskAvailability extends Component {
  constructor(props) {
    super(props);
    this.state = {
      localLoading: false,
      cloudLoading: false,
      showDialog: false,
      target_url: this.props.url,
      currentDetail: { pingObj: {} },
      cloudsList: [],
      localList: [],
      pagel: 1,
      limitl: 10,
      totall: 0,
      pagec: 1,
      limitc: 10,
      totalc: 0,
    };
    this.columns = [
      {
        key: 'created_at',
        dataIndex: 'created_at',
        title: '监测时间',
        render: (value) => (value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '-'),
      },
      {
        title: '监测节点数',
        dataIndex: 'nodelength',
        key: 'nodelength',
        render: (value, data) => data.httpd.length || '-',
      },
      {
        title: '监测成功节点数',
        dataIndex: 'successlength',
        key: 'successlength',
        render: (value, data) => data.httpd.filter((item) => !item.has_error).length,
      },
      {
        key: 'normal_status',
        dataIndex: 'normal_status',
        title: (
          <div>
            可用性状态
            <Helper
              placement="top"
              overlay="按HTTP响应状态码判定，检测处于200-299即可用性正常"
              className="paddingHelp"
            ></Helper>
          </div>
        ),
        render: (value) => {
            return <span style={{ color: STATUS_C[value] }}>{STATUS[value]}</span>;
        },
      },
    ];
  }
  componentDidMount() {
    this.getLocalData();
    this.getCloudData();
  }
  getLocalData() {
    this.props.setLoading(true);
    this.setState({ localLoading: true });
    getLocalReport(this.props.targetId, { page: this.state.pagel, limit: this.state.limitl }).then(
      (res) => {
        if (res.status === 'success') {
          const data = res.data?.details || [];
          const total = res.data.total || 0;
          this.setState({ localList: data, totall: total, localLoading: false });
        }
        this.props.setLoading(false);
      }
    );
  }
  getCloudData() {
    this.props.setLoading(true);
    this.setState({ cloudLoading: true });
    getCloudReport(this.props.targetId, { page: this.state.pagec, limit: this.state.limitc }).then(
      (res) => {
        this.props.setLoading(false);
        if (res.status === 'success') {
          const clouds = res.data?.clouds || [];
          clouds.forEach((c) => {
            c.key = c.event_id;
            const pings = c?.cloud?.detail_ping || [];
            let httpd = c?.cloud?.detail_http || [];
            httpd.map((item) => {
              pings.map((p) => {
                if (item.area === p.area) {
                  item.presp_time = p.resp_time;
                  item.created_at = c.created_at
                    ? moment(c.created_at).format('YYYY-MM-DD HH:mm:ss')
                    : '-';
                  item.pingObj = p;
                }
              });
            });
            c.httpd = httpd;
          });
          const total = res.data.total || 0;
          console.log('[ clouds ]-88', clouds);
          this.setState({ cloudsList: clouds, totalc: total, cloudLoading: false });
        }
      }
    );
  }
  onSearchChange = ({ page, limit, type }) => {
    if (type === 'local') {
      this.setState({ pagel: page, limitl: limit }, function () {
        this.getLocalData();
      });
    } else {
      this.setState({ pagec: page, limitc: limit }, function () {
        this.getCloudData();
      });
    }
  };
  setVal(detail, value) {
    this.setState({
      showDialog: value,
      currentDetail: detail,
    });
  }
  closeDailog() {
    this.setState({ showDialog: false });
    // this.setState({currentDetail: { pingObj: {} }})
  }
  // 判断哪个字段异常
  judgeError(data, num, unit, all) {
    // 域名解析速度 10s
    // ping探测 10s
    // http探测 60s
    // 页面读取速度 12s
    if (data!='-' && data > num) {
      if (all) {
        return (
          <>
            <span style={{ color: '#f04038' }}>{data + unit}</span>/{all.status_code}
          </>
        );
      } 
        return <span style={{ color: '#f04038' }}>{data + unit}</span>;
      
    } else {
      const time =data!='-' ? data + unit : data;
      if (all) {
        return (
          <>
          {time} / {all.status_code}
          </>
        );
      } 
      return time;
    }
  }
  header(header) {
    let hObj = {};
    try {
      hObj = JSON.parse(header);
    } catch {
      hObj = {};
    }
    if (Object.entries(hObj).length > 0) {
      return Object.entries(hObj).map(([k, v]) => {
        return (
          <>
            <p>{k}:</p>
            <p style={{ marginLeft: '1rem' }}>{v}</p>
          </>
        );
      });
    } else {
      return '暂无';
    }
  }
  renderItem(data) {
    return (
      <>
        {data.map((item) => {
          const {normal_status}=item
          return (
            <div className={s.siteitem}>
              <div className={cn(s.sitename)}>
               <span className={s.sitenameBe}  style={{background: STATUS_C[normal_status]}}></span> 监测点: {item.area || '-'}</div>
              <div>Ping响应时间: {this.judgeError(item.presp_time, 10000, 'ms')}</div>
              <div>
                HTTP响应时间/状态码:
                {this.judgeError(item.resp_time, 60000, 'ms', item)}
              </div>
              <div>域名解析速度: {this.judgeError(item.dns_time, 10000, 'ms')}</div>
              <div>页面读取速度: {this.judgeError(item.download_speed, 12000, 'ms')}</div>
              <span className={s.detailbtn} onClick={() => this.setVal(item, true)}>
                详情
              </span>
            </div>
          );
        })}
      </>
    );
  }
  render() {
    return (
      <div className={s.wangavatask}>
        <div className={s.title}>业务系统地址</div>
        <div className={s.itemwrap}>
          <p>{this.state.target_url || '-'}</p>
        </div>

        <div className={s.title}>
          可用性
          <Helper
            placement="top"
            overlay="统计任务可用性监控所有历史数据"
            className="paddingHelp"
          ></Helper>
        </div>
        <div className={s.subtitle}>本地监测</div>
        <Table
          columns={localScanColumns}
          loadingLabel=""
          data={this.state.localList}
        ></Table>
        {this.state.totall > 10 && (
          <Pagination
            key={Number(123)}
            className={s.pagination}
            current={this.state.pagel}
            showQuickJumper={{ goButton: true }}
            showSizeChanger={true}
            pageSize={this.state.limitl}
            pageSizeOptions={['10', '20', '50']}
            total={this.state.totall}
            showTotal={(total) => `共${total}条`}
            onChange={(page, size) => {
              this.onSearchChange({ page, limit: size, type: 'local' });
            }}
          />
        )}
        <div className={s.subtitle}>云端监测</div>
        <AntdTable
          bordered
          pagination={false}
          columns={this.columns}
          className="web_table"
          loading={this.state.cloudLoading ? { indicator: CusLoading } : false}
          expandable={{
            expandedRowRender: (record) => (
              <p style={{ margin: '-12px -20px', padding: '10px 0', background: '#fff' }}>
                {this.renderItem(record?.httpd)}
              </p>
            ),
            rowExpandable: (record) => record.event_id !== '',
            expandRowByClick: true,
            onExpand: (record, expandedRows) => {
              console.log(record, expandedRows, 999);
            },
          }}
          scroll={{
            x: '100%',
          }}
          dataSource={this.state.cloudsList}
        />
        {/* <Table columns={this.columns} data={this.state.cloudsList}></Table> */}
        {this.state.totalc > 10 && (
          <Pagination
            key={Number(123)}
            className={s.pagination}
            current={this.state.pagec}
            showQuickJumper={{ goButton: true }}
            showSizeChanger={true}
            pageSize={this.state.limitc}
            pageSizeOptions={['10', '20', '50']}
            total={this.state.totalc}
            showTotal={(total) => `共${total}条`}
            onChange={(page, size) => {
              this.onSearchChange({ page, limit: size, type: 'cloud' });
            }}
          />
        )}
        <Dialog
          className="wangDialog"
          title="监测详情"
          closable={true}
          cancelText=""
          confirmText="确定"
          onsubmit={() => this.closeDailog()}
          onhide={() => this.closeDailog()}
          visible={this.state.showDialog}
        >
          <div className={s.scandialog}>
            <div className={s.title}>HTTP监测</div>
            <div className={s.itemflex}>
              <div>
                <p>
                  监测点: <span>{this.state.currentDetail?.area || '-'}</span>
                </p>
                <p>
                  监测时间:{' '}
                  <span>
                    {this.state.currentDetail?.created_at
                      ? moment(this.state.currentDetail?.created_at).format('YYYY-MM-DD HH:mm:ss')
                      : '-'}
                  </span>
                </p>
                <p>
                  响应服务器IP: <span>{this.state.currentDetail?.ip || '-'}</span>
                </p>
                <p>
                  HTTP响应长度: <span>{this.state.currentDetail?.content_len!='-'? this.state.currentDetail?.content_len+ 'B' : '-'}</span>
                </p>
                <p>
                  响应状态码: <span>{this.state.currentDetail?.status_code }</span>
                </p>
                <p>
                域名解析速度: <span>{this.state.currentDetail?.dns_time!='-'?this.state.currentDetail?.dns_time + 'ms' : '-'}</span>
                </p>
                <p>
                  页面读取速度:{' '}
                  <span>
                    {this.state.currentDetail?.download_speed !== '-'
                      ? this.state.currentDetail?.download_speed + 'ms'
                      : '-'}
                  </span>
                </p>
                <p>
                  服务器连接耗时:{' '}
                  <span>{this.state.currentDetail?.ssl_shake_time!='-'? this.state.currentDetail?.ssl_shake_time+ 'ms': '-'}</span>
                </p>
                <p>
                  服务器响应耗时:{' '}
                  <span>{this.state.currentDetail?.response_time!='-'?this.state.currentDetail?.response_time + 'ms' : '-'}</span>
                </p>
                <p>
                  内容下载时间: <span>{this.state.currentDetail?.download_time!='-'?this.state.currentDetail?.download_time + 'ms' : '-'}</span>
                </p>
                <p>
                  总响应时间: <span>{this.state.currentDetail?.resp_time!='-'?this.state.currentDetail?.resp_time + 'ms' : '-'}</span>
                </p>
                <p>
                    监测结果: <span style={{color:STATUS_C[this.state.currentDetail?.normal_status]}}>{STATUS[this.state.currentDetail?.normal_status]}</span>
                  </p>
              </div>
              <div>{this.header(this.state.currentDetail?.header)}</div>
            </div>
            <div className={s.title}>Ping监测</div>
            <div className={s.itemflex}>
              <div>
                <p>
                  监测点: <span>{this.state.currentDetail?.area || '-'}</span>
                </p>
                <p>
                  监测时间:{' '}
                  <span>
                    {this.state.currentDetail?.created_at
                      ? moment(this.state.currentDetail?.created_at).format('YYYY-MM-DD HH:mm:ss')
                      : '-'}
                  </span>
                </p>
                <p>
                  响应主机IP: <span>{this.state.currentDetail?.pingObj?.ip || '-'}</span>
                </p>
                <p>
                  响应时间:{' '}
                  <span>{this.state.currentDetail?.pingObj?.resp_time + 'ms' || '-'}</span>
                </p>
                <p>
                  发送包数量:{' '}
                  <span>
                    {this.state.currentDetail?.pingObj?.packets_transmitted + '个' || '-'}
                  </span>
                </p>
                <p>
                  接收包数量:{' '}
                  <span>{this.state.currentDetail?.pingObj?.packets_received + '个' || '-'}</span>
                </p>
                <p>
                  丢包率:{' '}
                  <span>{this.state.currentDetail?.pingObj?.loss_rate * 100 + '%' || '0%'}</span>
                </p>
                {/* <p>
                  监测结果: <span>-</span>
                </p> */}
                {/* {this.state.currentDetail?.detail_http?.has_error?(<p>监测结果: <span className={s.safe}>正常</span></p>):(<p>监测结果: <span className={s.error}>异常</span></p>)} */}
              </div>
            </div>
          </div>
        </Dialog>
      </div>
    );
  }
}

export default TaskAvailability;
